﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasySL.Core;
using EasySL.Data.Interface;
using System.Reflection;
using EasySL.Share;

namespace EasySL.Service
{
    public partial class DataService
    {
        private readonly IDAL implDAL = DALFactory.CreateInstance();
        private readonly Cache cache = Cache.Instance;
        private Dictionary<string, MethodInfo> methods;
       
        public readonly static DataService Instance = new DataService();

        public DataService()
        {
            this.methods = new Dictionary<string, MethodInfo>();
            foreach (MethodInfo method in this.GetType().GetMethods())
            {
                var parameters = method.GetParameters().Select(p => p.Name).ToArray();
                this.methods.Add(string.Format("{0}({1})", method.Name, string.Join(",", parameters)), method);
            }
        }
        
        public string GetData(string requestString)
        {
            if (requestString == string.Empty)
                return this.Response(ResponseStatus.UnknownFailure, string.Empty, null);

            string responseString;

            try
            {
                Request request = new Request();
                request.Deserialize(requestString, methods);

                responseString = this.ExcuteMethod(request);

                return responseString;

            }
            catch (Exception ex)
            {
                return this.Response(ResponseStatus.ServiceException, ex.InnerException.Message, null);
            }
        }

        private string ExcuteMethod(Request request)
        {
            MethodInfo method = methods[request.MethodName];

            object responseObject = method.Invoke(this, request.GetParameterValues());
            string responseString = this.Response(ResponseStatus.Success, string.Empty, responseObject);

            return responseString;
        }


        protected string Response(ResponseStatus status, string message, object responseObject)
        {
            Response response = new Response();
            response.Status = status;
            response.Message = message;
            response.Data = responseObject;

            return response.Serialize();
        }

    }
}
